var express = require("express");
var router = express.Router();
var fs = require("fs");
var constJson = require("../../../../config/const.json"); //拿到系统字段。
const getHost = require("../../Api.ts");
var filesList = [];

//@Api(name="/rest/file/list")
router.get("/file/list", (req, res) => {
  console.log("[启动搜索]");
  function readFileList(path, fileList) {
    var files = fs.readdirSync(path);
    files.forEach(function (itm, index) {
      var stat = fs.statSync(path + itm);
      if (stat.isDirectory()) {
        //递归读取文件
        readFileList(path + itm + "/", fileList);
      } else {
        if (!itm.startsWith(".")) {
          var obj = { path: "", name: "", url: "",type:"" }; //定义一个对象存放文件的路径和名字
          obj.path = path.slice((constJson.root + constJson.directory).length); //路径
          obj.name = itm; //名字
          obj.url = getHost() + obj.path + obj.name;
          obj.type = itm.slice(itm.lastIndexOf(".")+1, itm.length);
          fileList.push(obj);
        }
      }
    });
  }
  var getFiles = {
    getFileList: function (path) {
      readFileList(path, filesList);
      console.log("[准备返回]");
      return filesList;
    },
  };
  if (filesList.length > 0) {
    res.send({
      code: 200,
      msg: "数据查询成功",
      data: filesList,
    });
  } else {
    res.send({
      code: 200,
      msg: "数据查询成功",
      data: getFiles.getFileList(constJson.root + constJson.directory + "/"),
    });
  }
});

module.exports = router;
